<?php
namespace ApigilityGroup\V1\Rest\Setting;

use ZF\ApiProblem\ApiProblem;
use ZF\Rest\AbstractResourceListener;
use Zend\ServiceManager\ServiceManager;
use ApigilityCatworkFoundation\Base\ApigilityResource;

class SettingResource extends ApigilityResource
{
    /**
     * @var \ApigilityGroup\Service\SettingService
     */
    protected $settingService;
    
    public function __construct(ServiceManager $services)
    {
        parent::__construct($services);
        $this->settingService = $this->serviceManager->get('ApigilityGroup\Service\SettingService');
    }
    
    /**
     * Create a resource
     *
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function create($data)
    {
        try {
            return new SettingEntity($this->settingService->createGroupSetting($data), $this->serviceManager);
        } catch (\Exception $exception) {
            return new ApiProblem($exception->getCode(), $exception->getMessage());
        }
    }

    /**
     * Delete a resource
     *
     * @param  mixed $id
     * @return ApiProblem|mixed
     */
    public function delete($id)
    {
        try {
            return $this->settingService->deleteGroupSetting($id);
        } catch (\Exception $exception) {
            return new ApiProblem($exception->getCode(), $exception->getMessage());
        }
    }

    /**
     * Fetch a resource
     *
     * @param  mixed $id
     * @return ApiProblem|mixed
     */
    public function fetch($id)
    {
        try {
            return new SettingEntity($this->settingService->getGroupSetting($id), $this->serviceManager);
        } catch (\Exception $exception) {
            return new ApiProblem($exception->getCode(), $exception->getMessage());
        }
    }

    /**
     * Fetch all or a subset of resources
     *
     * @param  array $params
     * @return ApiProblem|mixed
     */
    public function fetchAll($params = [])
    {
        try {
            if(isset($params->is_statistics) && $params->is_statistics){
                return new ApiProblem(200, $this->settingService->getGroupTotals($params));
            }else {
                return new SettingCollection($this->settingService->getGroupSettings($params), $this->serviceManager);
            }
        } catch (\Exception $exception) {
            return new ApiProblem($exception->getCode(), $exception->getMessage());
        }
    }

    /**
     * Patch (partial in-place update) a resource
     *
     * @param  mixed $id
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function patch($id, $data)
    {
        try {
            return new SettingEntity($this->settingService->updateGroupSetting($id, $data), $this->serviceManager);
        } catch (\Exception $exception) {
            return new ApiProblem($exception->getCode(), $exception->getMessage());
        }
    }
}
